package com.example.personnel_management_system.controller;

import com.example.personnel_management_system.entity.Roles;
import com.example.personnel_management_system.entity.User;
import com.example.personnel_management_system.service.IRolesService;
import com.example.personnel_management_system.service.IUserService;
import com.example.personnel_management_system.util.Result;
import com.example.personnel_management_system.util.Tool;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

@RestController
@RequestMapping("user")
public class UserController {
    @Autowired
    private IUserService userService;
    @Autowired
    private IRolesService rolesService;
    @Autowired
    private Tool tool;
    @RequestMapping("getCheckCode")
    public Result<String> getCheckCode(HttpServletRequest request){
        String CheckCode=tool.getCheckCode();
        request.getSession().setAttribute("CheckCode",CheckCode);
        return Result.success(CheckCode);
    }
    @RequestMapping("CheckUser")
    public Result<String>CheckUser(User user,String yzm,HttpServletRequest request){
        String CheckCode=(String)request.getSession().getAttribute("CheckCode");
        Roles roles=null;
        if(CheckCode==null||!CheckCode.equals(yzm)){
            return Result.failure("验证码错误");
        }else{
        User target=userService.findByIP(user);
        if(target==null){
            return Result.failure("账号密码错误");
        }
            request.getSession().setAttribute("UId",target.getuID());
            roles=rolesService.findByrID(target.getrID());
        }
        return Result.success(roles.getrType());
    }
    @RequestMapping("/addUser")
    public Result<Integer>addUser(User user){
    try{
        userService.insert(user);
        return Result.success(user.getuID());
    }catch (Exception e){
        return Result.failure();
    }
    }



}
